'use strict'
const fs = require('fs');
const router = require('koa-router')();

function getFiles(filesPath) {
    let path = filesPath || __dirname;
    let readFiles = fs.readdirSync(path)
    let routerFiles = readFiles.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    })
    return routerFiles;
}

function getRouter(router, routerFiles) {
    routerFiles.forEach(item => {
        let obj = require(__dirname + '/' + item);
        for(let key in obj){
            let routerArr = key.split(' ');
            let routerUrl = routerArr[1];
            let routerMethod = routerArr[0];
            let routerfuction = obj[key];
            if(routerMethod == 'get'){
                router.get(routerUrl,routerfuction)
            }else if(routerMethod == 'post'){
                router.post(routerUrl,routerfuction)
            }else if(routerMethod == 'delete'){
                router.delete(routerUrl,routerfuction)
            }else if(routerMethod == 'put'){
                router.put(routerUrl,routerfuction)
            }
        }
    })
    return router.routes();
}

module.exports = function(){
    let routerFiles = getFiles();
    let fn = getRouter(router,routerFiles);
    return fn;
}